import type { MockEndpoint, RouteParams } from './types'
import { authEndpoints } from './endpoints/auth'
import { taskEndpoints } from './endpoints/tasks'
import { logEndpoints } from './endpoints/logs'
import { settingsEndpoints } from './endpoints/settings'

// 合并所有端点
export const mockData: Record<string, MockEndpoint> = {
  ...authEndpoints,
  ...taskEndpoints,
  ...logEndpoints,
  ...settingsEndpoints
}

// 判断是否启用 Mock 模式
let mockEnabled = false

// 开启/关闭 Mock 模式
;(window as any)._debug = (enable: boolean) => {
  mockEnabled = enable
  console.log(`[Debug] Mock 模式已${enable ? '开启' : '关闭'}`)
}

// 添加状态检查函数
;(window as any)._debugStatus = () => {
  console.log(`[Debug] 当前 Mock 模式状态: ${mockEnabled ? '开启' : '关闭'}`)
  return mockEnabled
}

// 启动时显示状态
console.log(`[Debug] Mock 系统初始化完成，当前状态: ${mockEnabled ? '开启' : '关闭'}`)
console.log('[Debug] 使用 window._debug(true/false) 来开启/关闭 Mock 模式')
console.log('[Debug] 使用 window._debugStatus() 来查看当前状态')

// Mock 处理函数
export async function handleMockRequest(config: any): Promise<any> {
  const url = config.url || ''
  const method = (config.method || 'GET').toUpperCase()

  // 处理动态路由参数
  let routeParams: RouteParams = {}
  const mockEndpoint = Object.keys(mockData).find(pattern => {
    const regex = new RegExp('^' + pattern.replace(/:[^/]+/g, '([^/]+)') + '$')
    const match = url.match(regex)
    if (match) {
      // 提取路由参数
      routeParams = pattern.split('/')
        .filter(segment => segment.startsWith(':'))
        .reduce((acc, param, index) => ({
          ...acc,
          [param.slice(1)]: match[index + 1]
        }), {})
      return true
    }
    return false
  })

  if (mockEndpoint) {
    const endpoint = mockData[mockEndpoint as keyof typeof mockData]
    const mockResponse = endpoint[method as keyof typeof endpoint]
    if (mockResponse) {
      const data = config.data || {}
      // 传递完整URL以便端点函数解析查询参数
      const response = mockResponse(url, routeParams, data)
      
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 200))
      
      return {
        data: response,
        status: 200,
        statusText: 'OK',
        headers: {},
        config
      }
    }
  }

  throw new Error(`Mock endpoint not found: ${method} ${url}`)
}

// 检查是否启用 Mock 模式
export function isMockEnabled(): boolean {
  return mockEnabled
}

// 导出类型
export type { RouteParams, MockEndpoint, ExecutionRecord } from './types' 